package com.example.wyh.intelcheckbash;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.example.wyh.intelcheckbash.bug.BugInfoActivity;
import com.example.wyh.intelcheckbash.bug.BugRecordActivity;
import com.example.wyh.intelcheckbash.product_visit.ProductInfoActivity;
import com.example.wyh.intelcheckbash.product_visit.ScanNewPeoductVisitActivity;
import com.example.wyh.intelcheckbash.task.CheckDefectActivity;
import com.example.wyh.intelcheckbash.task.DownloadTaskActivity;
import com.example.wyh.intelcheckbash.task.TaskCheckActivity;
import com.example.wyh.intelcheckbash.task.UploadCheckedTaskActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by WYH on 17/9/20.
 */


public class HttpUtil {
    public static String ipClient = "http://www.chasingeda.com:7777/appsoft7";
//    public static String ipClient = "http://192.168.1.201:7001/appsoft7";
//    public static String ipClient = "http://10.46.3.126:7077";

    //get方式登录
    public static void requestNetForGetLogin(Context context, final String userName, String password, String deviceToken, final String deviceMac) {
        final Context mContext = context;
        final String mUserName = userName;
        final String mPassword = password;
        final String mDeviceToken = deviceToken;
        //在子线程中操作网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                //urlConnection请求服务器，验证

                ///appsoft7/appservlet/?requesttype=login&username=mUserName&password=111111&devicetoken=手机的IMEI&isjpush=1&plat=android&devicemac=手机wifi网卡的mac地址
                try {
                    //1：url对象
                    URL url= new URL(ipClient + "/appservlet/?requesttype=login&username="+mUserName+"&password="
                            + mPassword + "&devicetoken="+mDeviceToken+"&isjpush=1&plat=android&devicemac="+deviceMac);
                    Log.e("url",url.toString());
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5 * 1000);
                    int code = conn.getResponseCode();
                    Log.e("TAG","=====================服务器返回的信息code：：" + code);
                    if (code == 200) {
                        LoginActivity activity = (LoginActivity) mContext;
                        InputStream inputStream = conn.getInputStream();
                        String result = StreamUtils.readInputStreamToString(inputStream);
                        JSONObject jsonObject = new JSONObject(result);
                        jsonObject.put("userName",mUserName);
                        activity.jumpToMain(jsonObject,result);

                    }
                } catch (Exception e) {
                    Log.e("eeeee",e.getMessage());
                    if (e.getMessage().equals("connect timed out"))
                    {
                        LoginActivity activity = (LoginActivity) mContext;
                        activity.connectTimedOut("网络连接超时");
                    }else
                    {
                        LoginActivity activity = (LoginActivity) mContext;
                        activity.connectTimedOut("网络异常");
                    }
                }
            }
        }).start();
    }


    public static Thread requestNetForGetDownloadTask(final Context context, final String yhxtm, final String date, final String bc, final String deviceToken)
    {
        //在子线程中操作网络请求
        Thread thread =  new Thread(new Runnable() {
            @Override
            public void run() {
                byte[] arr = new byte[0];
                //urlConnection请求服务器，验证
                try {
                    //1：url对象
                    URL url= new URL(ipClient+"/appservlet/?requesttype=downloadjob&yhxtm="+
                            yhxtm+"&date="+date+"&bc="+bc+"&devicetoken="+deviceToken);
                    Log.e("url",url.toString());
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    InputStream inputStream = conn.getInputStream();
                    String strLength = conn.getHeaderField("contentlength");
                    int fileSize = Integer.parseInt(strLength);
                    Log.e("==========e","====lenght"+ strLength);
                    if (fileSize <= 0) {
                        Log.e("ss","无法获知文件大小 ");
                        throw new RuntimeException("无法获知文件大小 ");

                    } else if (inputStream == null) {
                        Log.e("ss","stream is null ");
                        throw new RuntimeException("stream is null");
                    } else {
                        // 把数据存入路径+文件名
                        int downLoadFileSize = 0;
                        DownloadTaskActivity activity = (DownloadTaskActivity) context;
                        activity.sendMsg(0, fileSize);

                        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len = 0;
                        while( (len=inputStream.read(buffer)) != -1 ){
                            outStream.write(buffer, 0, len);
                            downLoadFileSize += len;
                            activity.sendMsg(downLoadFileSize, fileSize);

                        }
//                        activity.sendMsgOk();
                        inputStream.close();
                        Message message = new Message();
                        message.obj = outStream.toString();
                        message.what = 0;
                        message.arg1 = getBcIndex(bc);
                        activity.saveAllData(message);
                        try {
                            Log.e("00","=========close=======");
                            inputStream.close();
                        } catch (Exception ex) {
                            Log.e("tag", "error: " + ex.getMessage(), ex);
                        }
                    }
                } catch (Exception e) {
                    if (e.getMessage().contains("No address associated with hostname"))
                    {
                        DownloadTaskActivity activity = (DownloadTaskActivity) context;
                        activity.sendNetWorkError();
                    }
                }
            }
        });
        return thread;
    }

    public static byte[] byteMerger(byte[] byte_1, byte[] byte_2){
//        byte_1 = new byte[] {68, 65, 84, 65, 32, 15, -58, 14};
//        byte_2 = new byte[] {68, 65, 84, 65, 35, 15, -67, 14, 113, 13, 96};

        byte[] byte_3 = new byte[byte_1.length+byte_2.length];
        System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
        System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
//        System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length - 4);
        return byte_3;
    }
    public  static  Integer getBcIndex(String key){
        if("白班".equals(key)) return 1;
        if("后夜班".equals(key)) return 0;
        return 2;
    }
    public  static  String getBcString(Integer index){
        if(index==1) return "白班";
        if(index ==0) return "后夜班";
        return "前夜班";
    }

    public static void requestNetForPostUploadData(final String yhxtm, final String devicetoken, final JSONObject data,final Context context) {
        new Thread(){
            public void run() {
                try {
                    //使用HttpURLConnection获得网络数据
                    URL url = new URL(ipClient+"/appservlet/?requesttype=uploadjob&yhxtm="
                            + yhxtm + "&devicetoken=" + devicetoken);
                    HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();
                    urlConnection.setConnectTimeout(1000);
                    urlConnection.setReadTimeout(1000);
                    urlConnection.setRequestMethod("POST");
                    urlConnection.connect();
                    String kk="data="+data.toString();
                    PrintWriter writer=new PrintWriter(urlConnection.getOutputStream());
                    writer.write(kk);
                    writer.flush();
                    writer.close();
                    int code=urlConnection.getResponseCode();
                    Log.e("code",code+"");
                    if (code==200) {
                        InputStream inputStream=urlConnection.getInputStream();
                        BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
                        String liner;
                        StringBuffer buffer=new StringBuffer();
                        while ((liner=reader.readLine())!=null) {
                            buffer.append(liner);

                        }
                        String str=buffer.toString();
                        JSONObject jsonResult = new JSONObject(str);
                        JSONArray uploadPKs = jsonResult.getJSONArray("data");
//                        Log.e("uploadPKs",uploadPKs.toString());
                        boolean isUploadSuccess = false;
                        for (int i = 0; i < uploadPKs.length(); i ++)
                        {
                            if (uploadPKs.getJSONObject(i).getString("pk").length() != 0)
                            {
                                isUploadSuccess = true;
                            }
                        }
                        TaskCheckActivity taskCheckActivity = (TaskCheckActivity)context;
                        taskCheckActivity.afterUploadSaveInLocal(isUploadSuccess,data);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    TaskCheckActivity taskCheckActivity = (TaskCheckActivity)context;
                    taskCheckActivity.afterUploadSaveInLocal(false,data);
                }

            };
        }.start();
    }

    public static void requestNetForPostUploadAllData(final String yhxtm, final String devicetoken, final JSONObject data, final Context context, final String key) {
        new Thread(){
            public void run() {
                try {

                    long a  =  new Date().getTime();
                    //使用HttpURLConnection获得网络数据
                    URL url = new URL(ipClient+"/appservlet/?requesttype=uploadjob&yhxtm="
                            + yhxtm + "&devicetoken=" + devicetoken);
                    HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();
                    urlConnection.setConnectTimeout(8000);
                    urlConnection.setReadTimeout(8000);
                    urlConnection.setRequestMethod("POST");

                    urlConnection.connect();
                    long b  =  new Date().getTime() -a ;
                    Log.e("连接网络需要时间是：", "======="+b);
                    String kk="data="+data.toString();
                    PrintWriter writer=new PrintWriter(urlConnection.getOutputStream());
                    writer.write(kk);
                    writer.flush();
                    writer.close();
//                    long c  =  new Date().getTime()-a-b;
//                    Log.e("=============content", "======="+c);
                    int code=urlConnection.getResponseCode();
                    if (code==200) {
                        InputStream inputStream=urlConnection.getInputStream();
                        BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
                        String liner;
                        StringBuffer buffer=new StringBuffer();
                        while ((liner=reader.readLine())!=null) {
                            buffer.append(liner);

                        }
                        String str=buffer.toString();
//                        long d  =  new Date().getTime() -a - b - c ;
//                        Log.e("str",str.toString());
//                        Log.e("=============content", "======="+d);

                        JSONObject jsonResult = new JSONObject(str);
                        JSONArray uploadPKs = jsonResult.getJSONArray("data");
                        boolean isUploadSuccess = false;
                        for (int i = 0; i < uploadPKs.length(); i ++)
                        {
                            if (uploadPKs.getJSONObject(i).getString("pk").length() != 0)
                            {
                                isUploadSuccess = true;
                            }
                        }
                        if (key.equals("UploadCheckedTaskActivity"))
                        {
                            UploadCheckedTaskActivity uploadCheckedTaskActivity = (UploadCheckedTaskActivity)context;
                            uploadCheckedTaskActivity.updateProgressBar(isUploadSuccess);
                        }
                        if (key.equals("CheckDefectActivity") && isUploadSuccess ==  true)
                        {
                            CheckDefectActivity checkDefectActivity = (CheckDefectActivity)context;
                            checkDefectActivity.updateProgressBar();
                        }
                        Log.e("返回的信息",str);
                    }
                } catch (Exception e) {
                    Log.e("上传结果失败",e.getMessage());
                    if (key.equals("UploadCheckedTaskActivity"))
                    {
                        UploadCheckedTaskActivity uploadCheckedTaskActivity = (UploadCheckedTaskActivity)context;
                        uploadCheckedTaskActivity.updateProgressBar(false);
                    }
                }

            };
        }.start();
    }

    public static void requestNetForUpdataPassword(final String username, final String password, final String newpassword, final Context context) {
        new Thread(){
            public void run() {
                try {

                    //使用HttpURLConnection获得网络数据
                    URL url = new URL(ipClient+"/appservlet/?requesttype=changepwd&username="
                            + username + "&password=" + password+"&newpassword="+newpassword);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(2 * 1000);
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        UpdatePasswordActivity activity = (UpdatePasswordActivity) context;
                        activity.updatePasswordCallback();
                    }

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                }

            };
        }.start();
    }

    public static void requestNetForUpdataApp(final String version, final Context context) {
        new Thread(){
            public void run() {
                try {
                    //使用HttpURLConnection获得网络数据
                    URL url = new URL(ipClient+"/appservlet/?requesttype=updateappversion&ver="+version+"&platform=Android");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(2 * 1000);
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        InputStream inputStream = conn.getInputStream();
                        String result = StreamUtils.readInputStreamToString(inputStream);
                        Log.e("=========result",result);
                        AboutActivity aboutActivity = (AboutActivity)context;
                        aboutActivity.downloadAPK(result);
                    }

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                }

            };
        }.start();
    }
    public static Date StrToDate(String str) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static String getSevenDaysDateString()
    {
        Date nowTime = new Date();
        //7天＊24小时＊60分＊60秒＊1000毫秒
        Date sevenDay = new Date(nowTime.getTime() - 7*24*60*60*1000);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(nowTime);
    }

    public static String getCurrentDateString()
    {
        Date nowTime = new Date();
//        Date currentDay = new Date(nowTime.getTime() - 4800000);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(nowTime);
    }
    public static String getCurrentDateStringOnlyDate()
    {
        Date nowTime = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return df.format(nowTime);
    }
    public static String getCurrentDateTimeString()
    {
        Date nowTime = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(nowTime);
    }
    public static void requestNetForCompleteTask(final String yhxtm,final String rwxtm, final String devicetoken, final String date,final Context context)
    {
        new Thread(){
            public void run() {
                try {

                    //http://www.chasingeda.com:7777/appsoft7/appservlet/?requesttype= completejob& yhxtm= 123& rwxtm=123& devicetoken=123& date=123
                    //使用HttpURLConnection获得网络数据
                    URL url = new URL(ipClient+"/appservlet/?requesttype=completejob&yhxtm="
                            + yhxtm + "&rwxtm="+ rwxtm + "&devicetoken=" + devicetoken + "date="+date);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(2 * 1000);
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        InputStream inputStream = conn.getInputStream();
                        String result = StreamUtils.readInputStreamToString(inputStream);
                        Log.e("result",result.toString());
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.getString("data").equals("success"))
                        {
                            TaskCheckActivity taskCheckActivity = (TaskCheckActivity)context;
                            taskCheckActivity.updateCompletedTask(rwxtm);
                        }
//                        UpdatePasswordActivity activity = (UpdatePasswordActivity) context;
//                        activity.updatePasswordCallback();
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    Log.e("eeee",e.toString());
//                    TaskCheckActivity taskCheckActivity = (TaskCheckActivity)context;
//                    taskCheckActivity.afterUploadSaveInLocal(false);
                }

            };
        }.start();
    }


    public static void requestNetForPostBugRecordData(final String yhxtm, final String devicetoken, final JSONObject data,final Context context,final String key) {
        new Thread(){
            public void run() {
                try {
                    //使用HttpURLConnection获得网络数据
                    URL url = new URL(ipClient+"/appservlet/?requesttype=uploadqx&yhxtm="
                            + yhxtm + "&devicetoken=" + devicetoken);
                    HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();
                    urlConnection.setConnectTimeout(1000);
                    urlConnection.setReadTimeout(1000);
                    urlConnection.setRequestMethod("POST");
                    urlConnection.connect();
                    String kk="data="+data.toString();
                    PrintWriter writer=new PrintWriter(urlConnection.getOutputStream());
                    writer.write(kk);
                    writer.flush();
                    writer.close();
                    int code=urlConnection.getResponseCode();
                    Log.e("code",code+"");
                    if (code==200) {
                        InputStream inputStream=urlConnection.getInputStream();
                        BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
                        String liner;
                        StringBuffer buffer=new StringBuffer();
                        while ((liner=reader.readLine())!=null) {
                            buffer.append(liner);

                        }
                        String str=buffer.toString();
                        JSONObject jsonResult = new JSONObject(str);
                        if (key.equals("BugRecordActivity"))
                        {
                            BugRecordActivity bugRecordActivity = (BugRecordActivity)context;
                            bugRecordActivity.uploadBugSuccess(jsonResult,data);
                        }
                        else if (key.equals("BugInfoActivity"))
                        {
                            BugInfoActivity bugInfoActivity = (BugInfoActivity)context;
                            bugInfoActivity.uploadBugSuccess(jsonResult,data);
                        }
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    if (key.equals("BugRecordActivity"))
                    {
                        BugRecordActivity bugRecordActivity = (BugRecordActivity)context;
                        bugRecordActivity.uploadBugFailed();
                    }
                    else if (key.equals("BugInfoActivity"))
                    {
                        BugInfoActivity bugInfoActivity = (BugInfoActivity)context;
                        bugInfoActivity.uploadBugFailed();
                    }
                }

            };
        }.start();
    }

    //自定义Toast弹框展示时间
    public static void showToast(final Activity activity, final String word, final long time) {
        activity.runOnUiThread(new Runnable() {
            public void run() {
                final Toast toast = Toast.makeText(activity, word, Toast.LENGTH_LONG);
                toast.show();
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        toast.cancel();
                    }
                }, time);
            }
        });
    }

    public static void requestNetForUpdateCheckOrigin(Context context, final String rwxtm, final String yhxtm) {
        final Context mContext = context;
        //在子线程中操作网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                //urlConnection请求服务器，验证

                ///appsoft7/appservlet/?requesttype=login&username=mUserName&password=111111&devicetoken=手机的IMEI&isjpush=1&plat=android&devicemac=手机wifi网卡的mac地址
                try {
                    //1：url对象
//                    appservlet?requesttype=updatetaskarea&rwxtm=*****&yhxtm=
                    URL url= new URL(ipClient + "/appservlet/?requesttype=updatetaskarea&rwxtm="+rwxtm+"&yhxtm="
                            + yhxtm);
                    Log.e("url",url.toString());
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5 * 1000);
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        StatisticalCheckActivity activity = (StatisticalCheckActivity) mContext;
                        InputStream inputStream = conn.getInputStream();
                        String result = StreamUtils.readInputStreamToString(inputStream);
                        JSONObject jsonObject = new JSONObject(result);
                        String status = jsonObject.getString("status");
                        if (status.equals("success"))
                        {
                            activity.updatetaskarea(jsonObject.getJSONObject("data"));
                        }
                        Log.e("更新任务区域信息",jsonObject.toString());


                    }
                } catch (Exception e) {
                    Log.e("eeeee",e.getMessage());
//                    if (e.getMessage().equals("connect timed out"))
//                    {
//                        LoginActivity activity = (LoginActivity) mContext;
//                        activity.connectTimedOut("网络连接超时");
//                    }else
//                    {
//                        LoginActivity activity = (LoginActivity) mContext;
//                        activity.connectTimedOut("网络异常");
//                    }
                }
            }
        }).start();
    }


    public static void requestNetForPostProductVisitData(final JSONObject data,final Context context ,final String type) {
        new Thread(){
            public void run() {
                try {
                    //使用HttpURLConnection获得网络数据
                    URL url = new URL(ipClient+"/appservlet/?requesttype=scyxxs");
                    HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();
                    urlConnection.setConnectTimeout(3000);
                    urlConnection.setReadTimeout(3000);
                    urlConnection.setRequestMethod("POST");
                    urlConnection.connect();

                    String kk="data="+data.toString();
                    PrintWriter writer=new PrintWriter(urlConnection.getOutputStream());
                    writer.write(kk);
                    writer.flush();
                    writer.close();
                    int code=urlConnection.getResponseCode();
                    Log.e("code",code+"");
                    if (code==200) {
                        InputStream inputStream=urlConnection.getInputStream();
                        BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
                        String liner;
                        StringBuffer buffer=new StringBuffer();
                        while ((liner=reader.readLine())!=null) {
                            buffer.append(liner);

                        }
                        String str=buffer.toString();
                        JSONObject jsonResult = new JSONObject(str);
                        Log.e("jsonResult=========",jsonResult.toString());
                        if (type.equals("ScanNewPeoductVisitActivity"))
                        {
                            ScanNewPeoductVisitActivity scanNewPeoductVisitActivity = (ScanNewPeoductVisitActivity)context;
                            scanNewPeoductVisitActivity.uploadProductSuccess(jsonResult,data);
                        }
                        else if (type.equals("ProductInfoActivity"))
                        {
                            ProductInfoActivity productInfoActivity = (ProductInfoActivity)context;
                            productInfoActivity.uploadProductSuccess(jsonResult,data);
                        }

                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    Log.e("eeeee",e.getMessage());
                    if (type.equals("ScanNewPeoductVisitActivity"))
                    {
                        ScanNewPeoductVisitActivity scanNewPeoductVisitActivity = (ScanNewPeoductVisitActivity)context;
                        scanNewPeoductVisitActivity.uploadProductFailed();
                    }else if (type.equals("ProductInfoActivity"))
                    {
                        ProductInfoActivity productInfoActivity = (ProductInfoActivity)context;
                        productInfoActivity.uploadProductFailed();
                    }


                }

            };
        }.start();
    }

}
